package com.mobilepay.moneypig.model.activity.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseActivity;
import com.mobilepay.moneypig.base.NoDoubleClickListener;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.activity.mine.AddCreditActivity;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.model.dialog.CreditDialog;
import com.mobilepay.moneypig.model.dialog.PasswordDialog;
import com.mobilepay.moneypig.model.dialog.VerifyDialog;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.pay.CollectData;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by xlm on 2017/8/2 0002
 */

public class BankPayActivity extends BaseActivity {

    private RelativeLayout mRelativeBack;
    private TextView mTextTime, mTextMoney, mTextChooseCd;
    private EditText mEditCvn;
    private TextView mEditUserTime;
    private Button mButtonCommit;
    private String amount;
    private int collectype;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.activity_bank_pay);
    }

    @Override
    protected void initViews() {
        mRelativeBack = (RelativeLayout) findViewById(R.id.bankpay_back);
        mTextTime = (TextView) findViewById(R.id.bankpay_time);
        mTextMoney = (TextView) findViewById(R.id.bankpay_money);
        mTextChooseCd = (TextView) findViewById(R.id.bankpay_choose);
        mEditCvn = (EditText) findViewById(R.id.bankpay_cvn2);
        mEditUserTime = (TextView) findViewById(R.id.bankpay_usetime);
        mButtonCommit = (Button) findViewById(R.id.bankpay_commit);
    }

    @Override
    protected void onGetIntent(Intent intent) {
        out_trade_no = intent.getStringExtra("out_trade_no");
        amount = intent.getStringExtra("amount");
        collectype = intent.getIntExtra("collect_type", 0);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        mTextTime.setText(CommonUtil.getCurrentDate("yyyy-MM-dd HH:mm:ss"));
        mTextMoney.setText("￥" + amount);
    }

    private static final int PERMISSON_PHONE = 2;

    /**
     * 检查权限，因为android6.0有些权限需要用户确认授权
     */

    private void checkPermission() {
        if (checkReadPhoneStatePermission(PERMISSON_PHONE)) {
            commitData();
        }
    }

    @Override
    public void onReadPhoneStatePermission(int result_code, boolean result) {
        if (result) {
            checkPermission();
        } else {
            showToastShort("拒绝此权限，您将无法使用该功能");
        }
    }

    @Override
    protected void onSetListener() {
        mRelativeBack.setOnClickListener(this);
        mButtonCommit.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View view) {
                super.onNoDoubleClick(view);
                checkPermission();
            }
        });
        mTextChooseCd.setOnClickListener(this);
        mEditUserTime.setOnClickListener(this);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (mVerifyDialog != null && mVerifyDialog.isShowing()) {
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bankpay_back:
                finish();
                break;
            case R.id.bankpay_choose:
                showDailog();
                break;
            case R.id.bankpay_usetime:
                showTimePicker();
                break;
        }
    }

    String mobile = "";
    String cardId = "";
    String out_trade_no = "";
    String cards_expire;
    String cards_cvv2;
    private CreditDialog creditDialog;

    private void showDailog() {
        if (creditDialog == null) {
            creditDialog = new CreditDialog(getThis());
        }
        creditDialog.setCancelable(true);
        creditDialog.upDateCreditList();
        creditDialog.setListener(new CreditDialog.Listener() {
            @Override
            public void onMobile(String phone, String card, String id) {
                super.onMobile(phone, card, id);
                if (CommonUtil.isEmpty(phone)) {
                    startActivity(AddCreditActivity.class, false, false);
                } else {
                    mobile = phone;
                    cardId = id;
                    mTextChooseCd.setText(CommonUtil.StringOpt(card, 3, card.length() - 4));
                }
            }
        });
        creditDialog.show();
    }

    private TimePickerView pvTime;

    private void showTimePicker() {
        Calendar calendar = Calendar.getInstance();
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                cards_expire = getTime(date);
                mEditUserTime.setText(getTime(date));
            }
        })
                .setType(new boolean[]{true, true, false, false, false, false})//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setSubmitColor(Color.parseColor("#e46641"))
                .setCancelColor(Color.parseColor("#e46641"))
                .setSubCalSize(14)
                .setContentSize(20)//滚轮文字大小
                .setTitleSize(16)//标题文字大小
                .setTitleText("请选择有效期")//标题文字
                .setLineSpacingMultiplier(1.9f)
                .isCenterLabel(true)
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setTitleBgColor(Color.parseColor("#ffffff"))//标题背景颜色 Night mode
                .setBgColor(Color.parseColor("#ffffff"))//滚轮背景颜色 Night mode
                .setDate(calendar)// 默认是系统时间*/
                .setLabel("年    ", "月    ", "日", "时", "分", "秒")
                .build();
        pvTime.show();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        return format.format(date);
    }

    private void commitData() {
        cards_cvv2 = mEditCvn.getText().toString();
        if (CommonUtil.isEmpty(mobile)) {
            showToastShort("请选择信用卡");
            return;
        }
        if (CommonUtil.isEmpty(cards_cvv2)) {
            showToastShort("请输入卡背面CVN2号码");
            return;
        }
        if (CommonUtil.isEmpty(cards_expire)) {
            showToastShort("请选择有效期");
            return;
        }
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", collectype == 1 ? NetConfig.joinpay_fast : NetConfig.helipay_fast);
        param.add("uid", String.valueOf(App.getApp().getUserDetailInfo().getData().getUid()));
        param.add("out_trade_no", out_trade_no);
        param.add("cards_cvv2", cards_cvv2);
        param.add("creditcard_id", cardId);
        param.add("mobile", mobile);
        if (collectype == 2) {
            param.add("cards_expire", cards_expire.substring(2, cards_expire.length()));
            param.add("imei", CommonUtil.getDEVICE_ID(getApplicationContext()));
        } else
            param.add("cards_expire", cards_expire);
        param.add("sign", param.getMd5String());
        showProgress("支付处理中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    showToastShort(responseResult.getInfo());
                    if (responseResult.getStatus() == 1) {
                        CollectData collectData = GsonUtil.GsonToBean(string, CollectData.class);
                        if (collectData.getData().getIs_first() == 1) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showVerifyDialog();
                                }
                            });
                        }
//                        else if (collectData.getData().getIs_first() == 0) {
//                            finishActivity(true);
//                        }
                    }
                }
            }
        });
    }

    private VerifyDialog mVerifyDialog;

    private void showVerifyDialog() {
        if (mVerifyDialog == null) {
            mVerifyDialog = new VerifyDialog(this);
        }
        mVerifyDialog.setCancelable(false);
        mVerifyDialog.show();
        mVerifyDialog.setListener(new PasswordDialog.Listener() {
            @Override
            public void onCancle() {
                super.onCancle();
                finish();
            }

            @Override
            public void onConfirm(String ps) {
                mVerifyDialog.dismiss();
                if (CommonUtil.isEmpty(ps)) {
                    showToastShort("请输入验证码");
                } else {
                    submitData(ps);
                }
            }
        });
    }

    private void submitData(String verify) {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.helipay_fast_submit);
        param.add("uid", String.valueOf(App.getApp().getUserDetailInfo().getData().getUid()));
        param.add("out_trade_no", out_trade_no);
        param.add("verify", verify);
        param.add("creditcard_id", cardId);
        param.add("sign", param.getMd5String());
        showProgress("支付处理中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                if (CommonUtil.isForeground(getThis())) {
                    showToastShort(getString(R.string.net_state));
                }
            }

            @Override
            public void onHttpSuccess(String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                if (HttpUtils.isJson(string)) {
                    ResponseResult responseResult = GsonUtil.GsonToBean(string, ResponseResult.class);
                    showToastShort(responseResult.getInfo());
//                    if (responseResult.getStatus() == 1) {
//                        finishActivity(true);
//                    }
                }
            }
        });
    }
}
